package com.wuercloud.http.client;

import com.wuercloud.http.json.codec.HttpJsonRequest;
import com.wuercloud.http.json.codec.HttpJsonResponse;
import com.wuercloud.http.json.pojo.InfoObject;
import com.wuercloud.utils.FastJsonUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by JiangWL on 2017/2/14.
 */
public class HttpJsonClientHandler extends ChannelInboundHandlerAdapter {
    private static Logger log = LoggerFactory.getLogger(HttpJsonClientHandler.class);
    private static ThreadLocal<InfoObject> infoObjectThreadLocal = new ThreadLocal<>();
    //private InfoObject object = null;

    public HttpJsonClientHandler(final InfoObject obj){
        infoObjectThreadLocal.set(obj);
        //this.object = obj;
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info(" 连接上服务器...");
        HttpJsonRequest request = new HttpJsonRequest(null, this.infoObjectThreadLocal.get());
        ctx.writeAndFlush(request);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info(msg.getClass().getName());
        if (msg instanceof HttpJsonResponse){
            HttpJsonResponse response = (HttpJsonResponse)msg;
            InfoObject info = (InfoObject) response.getResult();
            log.info("接收到了ID为"+info.getId()+"的数据，详细信息内容：" + FastJsonUtils.objectToJson(info));
        }

        //System.out.println("接收到了数据..." + msg);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
